package com.example.mqtt_demo

import androidx.lifecycle.MutableLiveData
import org.fusesource.hawtbuf.UTF8Buffer
import org.fusesource.mqtt.client.*


object ReceiverMessageHelper {
    private val _messagePublisher = MutableLiveData<String>()

    val messagePublisher
        get() = _messagePublisher

    private var isRunningFlag = false
    private val mConnection: FutureConnection

    init {
        mConnection = initMqtt("10.120.16.40", 1883)
        subscribeTopics(mConnection, listOf("_Leiii_Receiver"))
    }

    fun startReceiverThread() {
        isRunningFlag = true

        Thread({
            while (isRunningFlag) {
                receiveMessages(mConnection)?.let {
                    _messagePublisher.postValue(String(it.payload))
                }
                Thread.sleep(1000)
            }
        }, "MQTT-Receiver").start()
    }

    fun stopReceiverThread() {
        isRunningFlag = false
    }

    private fun initMqtt(host: String, port: Int): FutureConnection {
        val mqtt = MQTT()
        mqtt.setHost(host, port)
        val connection = mqtt.futureConnection()
        connection.connect()
        return connection
    }

    fun subscribeTopics(connection: FutureConnection, topics: List<String>) {
        for (topic in topics) {
            connection.subscribe(arrayOf(Topic(UTF8Buffer(topic), QoS.AT_LEAST_ONCE)))
        }
    }

    fun receiveMessages(connection: FutureConnection): Message? {
        // Begin to receive messages from above topic
        val receive = connection.receive()
        return receive.await()
    }
}